﻿using System;
using System.Diagnostics.Contracts;
using System.Windows;

namespace OpenLS.Spreadsheet.UI.Internals
{
    class CellArrangeInfo
    {
        private readonly Rect _cellRect;
        private readonly Cell _cell;
        private readonly ClusteredCellTextControl.CellLayoutManager _manager;

        private HorizontalBounds? _maxBoundsWithOverflowCache;
        private double _clusterXOrigin;

        public HorizontalBounds MaxBoundsWithOverflow
        {
            get
            {
               //\\ Contract.Ensures(Contract.Result<double>() >= 0);
                if (!Cell.CanOverflow)
                    return new HorizontalBounds(_cell.Column.Offset, _cell.Column.Offset+  CellWidth);
                if (_maxBoundsWithOverflowCache != null)
                    return _maxBoundsWithOverflowCache.Value;
                var bounds = _manager.GetMaxBoundsWithOverflow(_cell, _cellRect);
             //   bounds = bounds.Offset(-Math.Min(bounds.Min, _clusterXOrigin));
                bounds = new HorizontalBounds(Math.Max(bounds.Min - _clusterXOrigin, 0), Math.Max(bounds.Max - _clusterXOrigin, 0));
                //bounds = bounds.Offset(-_clusterXOrigin);
                _maxBoundsWithOverflowCache = bounds;
                
                return _maxBoundsWithOverflowCache.Value;
            }
        }
        public double CellWidth
        {
            get
            {
                Contract.Ensures(Contract.Result<double>() >= 0);
                return _cellRect.Width;
            }
        }
        public double CellHeight
        {
            get
            {
                Contract.Ensures(Contract.Result<double>() >= 0);
                return _cellRect.Height;
            }
        }
        public Cell Cell { get
        {
            Contract.Ensures(Contract.Result<Cell>() != null);
            return _cell;
        } }

        public Rect CellRect
        {
            get { return _cellRect; }
        }

        public Point CellOrigin
        {
            get { return _cellRect.TopLeft; }
        }

        public CellArrangeInfo(Rect cellRect, Cell cell,  ClusteredCellTextControl.CellLayoutManager manager, double clusterOrigin)
        {
            this._clusterXOrigin = clusterOrigin;
            _cellRect = cellRect;
            _cell = cell;
            _manager = manager;
        }

        public bool NeedsClip(Size size)
        {
            switch(_cell.HorizontalAlignment)
            {
                case HorizontalCellAlignment.Center:
                    case HorizontalCellAlignment.CenterContinuous:
                    return true;
            }
            if(size.Height > CellHeight)
                return true;
            if (size.Width > CellWidth && size.Width > MaxBoundsWithOverflow.Width)
                return true;
            return false;
        }
    }
}